import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, PixelRatio, KeyboardAvoidingView, Platform, ScrollView, TouchableOpacity, Alert } from 'react-native';
import { FormItem } from '../../../components/form/formItem';
import { Button } from '../../../components/form/button';
import { GLOBAL } from '../../../config/global';
import { purchaseTag, saleTag, currency } from './_components/common';
import RadioButton from '../../../components/form/radioButton';
import Dictionary from '../../../utils/dictionary';
import { Common } from '../../../component/common/Common.js';
import DateGapPicker from '../../../components/common/DateGapPicker';
import { API, API_GENERATE } from '../../../config/api';
import MethodUtil from '../../../utils/MethodUtil';
import HTTP from '../../../utils/http';
import ToastUtil from '../../../utils/toast';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { style } from '../../../theme/style';
import { Header } from 'react-navigation';
import { ProgressModal } from '../../../components/common/ProgressModal';
import { CommonDialog } from '../../../components/common/Dialog';
import { STORAGE_CONSTANT } from '../../../config/storage';
import StorageHelper from '../../../utils/storageHelper';
import { ProductInfoItem } from './_components/ProductInfoItem';
import OrderNewOilCreactService from '../_common/service';
import { NavigationEvents } from 'react-navigation';

const scale = GLOBAL.SCALE;
import moment from 'moment';
import navigationSeevice from '../../../components/navigation/navigationSeevice';
const arrowDownImage = require('../../../imgs/Group.png');
const timeImage = require('../../../imgs/time.png');
export class SinoNewOrderBaseInfoPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		let { tCode } = navigation.state.params;
		let { orderId, bizMode, orderType, statusName } = navigation.state.params.paramsData || {};
		tCode = tCode ? tCode : bizMode == 1 ? 'SINONEWC' : orderType === 'P' ? 'SINONEWP' : 'SINONEWS';
		let title = tCode === 'SINONEWC' ? '闭口' : tCode === 'SINONEWP' ? '采购' : '销售';
		title = orderId ? `中新油${title}成交报告-${statusName || '草稿'}` : `中新油${title}成交报告`;
		return {
			headerTitle: title,
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack(); }} color='#fff' />,
			headerRight: null,
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			},
			gesturesEnabled: false  //禁止侧滑返回事件
		}
	};
	constructor(props) {
		super(props);
		let { submitAgain, tCode, paramsData } = props.navigation.state.params;
		this.tCode = tCode || '';
		this.submitAgain = submitAgain; //判断是否是变更
		let { orderId } = paramsData || {};
		this.orderId = orderId;
		this.state = {
			status: 'data',
			contractTypeIndex: 0,
			modalObj: {
				currSelectIndex: -1,
				currTitle: '',
				currlistData: [],
				currCb: null,
				currIsVisible: false,
			},
			openDatePicker: false,
			POrderInfo: {},//采购
			SOrderInfo: {},//销售
			purchaseOrderStatus: null, // 是否作废状态 1-作废 2-正常
			purchaseOrderId: '', // 外采订单号
			fee: [], //费用
			contractTypes: {}, //长约类型
			goods: [],//商品
			payMethod: [],//付款方式
			otherInfo: {
				beginAddress: '',
				endAddress: '',
				priceTerm: '',
				remark: ''
			},
			lightBoxData: {
				modalVisible: false,
				onClosePress: this._closeLightBox,
				title: '',
				rowDataList: [],
			},
			modalVisible: false
		}
		this.requesting = false;
		this.currPayMethod = {};
		this.currCurrencyIndex = -1;

		this.termsData = [];	//贸易条件
		// this.deliveryData = [];	//交货方式
		this.SPayMethodData = [];//收/付款方式-销
		this.PPayMethodData = [];//收/付款方式-采
		this.oldSPayMethodData = [];//收/付款方式-销(存)
		this.oldPPayMethodData = [];//收/付款方式-采(存)
		this.currencyData = [];	//币种
		this.feeData = [];
		this.departmentList = []; // 部门选择
		this.dateObj = {};
		this.groupOnoff = null;
	}

	async componentWillMount() {
		await this.getDictList();
		this.userInfo = await this._getUserInfo();
		this.initData();
	}

	initData() {
		if (this.orderId) {
			this.editInit();
		} else {
			this.addPayMethod();
			this.initFee();
		}
	}

	_getUserInfo = async () => {
		//获取用户信息
		let userInfo = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		if (userInfo) {
			userInfo = JSON.parse(userInfo);
		}
		return userInfo || {};
	}

	editInit = async () => {
		this.setState({ status: 'loading' });
		let responseData = await HTTP.GET(API_GENERATE(API.ZXY_ORDER_INFO), { orderId: this.orderId });
		this.setState({ status: 'data' });
		if (responseData) {
			let { oppoPurOrderInfoVO, oppoSaleOrderInfoVO, zxyOrderInfoVO, zxyOrderFeeVOs, zxyOrderItemVOs, zxyOrderPayMethodVOs, zxyPurOrderPayMethodVOs, zxySaleOrderPayMethodVOs, oppoTypeOrderInfoVO } = responseData;
			let { POrderInfo, SOrderInfo, fee, goods, payMethod, otherInfo, contractType, contractTypes } = this.state;
			fee = zxyOrderFeeVOs;
			goods = zxyOrderItemVOs;
			if (!zxyOrderInfoVO) {
				this.tCode = 'SINONEWC';
				this.processInstanceId = oppoPurOrderInfoVO.cancelProcessInstanceId || oppoPurOrderInfoVO.processInstanceId;
				this.statusName = oppoSaleOrderInfoVO.statusName || '';
				this.status = oppoSaleOrderInfoVO.status || '';
				POrderInfo = oppoPurOrderInfoVO;
				SOrderInfo = oppoSaleOrderInfoVO;
				contractTypes = oppoPurOrderInfoVO;
				contractTypes = oppoSaleOrderInfoVO;
				payMethod = zxyPurOrderPayMethodVOs.map((item, index) => {
					return { PPayMethod: item, SPayMethod: zxySaleOrderPayMethodVOs[index] };
				})
				otherInfo.remark = POrderInfo.remark;
				otherInfo.beginAddress = POrderInfo.beginAddress;
				otherInfo.endAddress = POrderInfo.endAddress;
				otherInfo.priceTerm = POrderInfo.priceTerm;
				otherInfo.priceTermDesc = POrderInfo.priceTermDesc;
				this.profit = this.getProfit(goods);
			} else if (zxyOrderInfoVO.orderType === 'P') {
				contractTypes = zxyOrderInfoVO;
				this.tCode = `SINONEWP`;
				this.processInstanceId = zxyOrderInfoVO.cancelProcessInstanceId || zxyOrderInfoVO.processInstanceId;
				this.statusName = zxyOrderInfoVO.statusName || '';
				this.status = zxyOrderInfoVO.status || '';
				POrderInfo = zxyOrderInfoVO;
				payMethod = zxyOrderPayMethodVOs.map(item => {
					return { PPayMethod: item };
				});
				otherInfo.remark = POrderInfo.remark;
				otherInfo.beginAddress = POrderInfo.beginAddress;
				otherInfo.endAddress = POrderInfo.endAddress;
				otherInfo.priceTerm = POrderInfo.priceTerm;
				otherInfo.priceTermDesc = POrderInfo.priceTermDesc;
			} else if (zxyOrderInfoVO.orderType === 'S') {
				this.tCode = `SINONEWS`;
				this.processInstanceId = zxyOrderInfoVO.cancelProcessInstanceId || zxyOrderInfoVO.processInstanceId;
				this.status = zxyOrderInfoVO.status || '';
				SOrderInfo = zxyOrderInfoVO;
				contractTypes = zxyOrderInfoVO;
				payMethod = zxyOrderPayMethodVOs.map(item => {
					return { SPayMethod: item };
				});
				otherInfo.remark = SOrderInfo.remark;
				otherInfo.beginAddress = SOrderInfo.beginAddress;
				otherInfo.endAddress = SOrderInfo.endAddress;
				otherInfo.priceTerm = SOrderInfo.priceTerm;
				otherInfo.priceTermDesc = SOrderInfo.priceTermDesc;
				if (zxyOrderInfoVO.companyId == this.userInfo.companyId) {
					this.getCancelInfo();
				}
			}
			if (this.statusName) {
				let { paramsData } = this.props.navigation.state.params;
				paramsData.statusName = this.statusName;
				this.props.navigation.setParams({ paramsData })
			}
			this.setState({
				POrderInfo,//采购
				SOrderInfo,//销售
				fee, //费用
				goods,//商品
				payMethod,//付款方式
				otherInfo,
				contractTypes, // 长约类型
			})
		}
	}

	// 获取订单是否作废信息
	getCancelInfo = async () => {
		let res = await HTTP.POST(API_GENERATE(API.ZXY_CANCEL_INFO), { orderId: this.orderId });
		if (res && res.status) {
			this.setState({
				purchaseOrderStatus: res.status,
				purchaseOrderId: res.orderId
			})
		}
	}

	getProfit = (goods) => {
		let profit = 0;
		goods.map(item => {
			let sum = MethodUtil.countObj.subtract(Number.parseFloat(item.nakedSalePrice), Number.parseFloat(item.nakedPrice));
			profit += MethodUtil.countObj.multiply(sum, Number.parseFloat(item.quantity));
		})
		return profit;
	}

	initFee = () => {
		let fee = [];
		this.feeData.map((item, index) => {
			fee.push({ currency: 'USD', feeAmt: '', logisticFundType: item.dictKey, logisticFundTypeName: item.dictName })
		})
		this.setState({ fee });
	}

	addPayMethod = () => {

		let payMethodObj = { payMethod: '', paymentDays: '', paymentRatio: '' };
		let { payMethod } = this.state;
		payMethod.push({});
		if (this.tCode !== 'SINONEWP') {//非采购
			payMethod[payMethod.length - 1].SPayMethod = {};
		}
		if (this.tCode !== 'SINONEWS') {//非销售
			payMethod[payMethod.length - 1].PPayMethod = {};
			Object.assign(payMethod[payMethod.length - 1].PPayMethod, payMethodObj)
		}

		this.setState({ payMethod });
	}

	//获取数据库字典
	async getDictList() {
		this.termsData = await Dictionary.get('EC_ZXY_OT_DELIVERY_TYPE') || [];
		this.deliveryData = await Dictionary.get('EC_ZXY_SALES_DELIVERY_TYPE') || [];
		this.SPayMethodData = await Dictionary.get('EC_ZXY_PAY_METHOD') || [];
		this.PPayMethodData = await Dictionary.get('EC_ZXY_PAY_METHOD') || [];
		this.oldSPayMethodData = this.SPayMethodData;
		this.oldPPayMethodData = this.PPayMethodData;
		this.currencyData = await Dictionary.get('EC_ZXY_CURRENCY') || [];
		this.feeData = await Dictionary.get('ZXY_SETTLEMENT_FEE_DETAIL_TYPE') || [];
		let dictionaryData = await HTTP.GET(API_GENERATE(API.GET_ORGAN_LIST));
		this.contractType = await Dictionary.get('EC_OD_LONG_TERM') || [];
		this.endAddressData = await Dictionary.get('OD_ZXY_PORT') || [];
		console.log("this.endAddressData", this.endAddressData)
		dictionaryData.forEach(element => {
			// 隐藏展示“区域营销管理部、中新油石化业务部门”
			if (element.organId != 'N002-21' && element.organId != 'N002-A0') {
				this.departmentList.push({ dictKey: element.organId, dictName: element.organName })
			}
		});
	}

	//选择供应商或者客户
	gotoSupplier(type) {
		let params = {
			type: 'SinoNewOrderBaseInfoPage',
			isForeign: 1,
			queryType: 'ZXY_ORDER_ADD',
			bizMode: this.tCode !== 'SINONEWC' ? '0' : '1',
			isAll: true,
			orderType: type
		}
		if (this.tCode !== 'SINONEWC') {
			params.orderType = this.tCode === 'SINONEWP' ? 'P' : 'S';
		}
		this.props.navigation.navigate('SeachSupplierPage', {
			...params,
			callBack: (data) => {
				let { companyId, companyName, creditLevel } = data || {};
				// if (this.state[`${type}OrderInfo`].companyId !== companyId) {
				// 	this.state.goods = [];
				// }
				this.state[`${type}OrderInfo`].companyId = companyId;
				this.state[`${type}OrderInfo`].companyName = companyName;
				this.state[`${type}OrderInfo`].creditLevel = creditLevel;

				// if ('1' != data.isZxyCreditShow) { //1 化销
				// 	let lsPArr = [];
				// 	let lsSArr = [];
				// 	if (type == 'P') {
				// 		this.oldPPayMethodData && this.oldPPayMethodData.forEach((item, index) => {
				// 			if (item.segment == "FALSE") {
				// 				lsPArr.push(item);
				// 			}
				// 		})
				// 		this.PPayMethodData = lsPArr;
				// 	}
				// 	if (type == 'S') {
				// 		this.oldSPayMethodData && this.oldSPayMethodData.forEach(item => {
				// 			if (item.segment == "FALSE") {
				// 				lsSArr.push(item);
				// 			}
				// 		})
				// 		this.SPayMethodData = lsSArr;
				// 	}
				// } else {
				// 	this.SPayMethodData = this.oldSPayMethodData;
				// 	this.PPayMethodData = this.oldPPayMethodData;
				// }
				this.SPayMethodData = this.oldSPayMethodData;
				this.PPayMethodData = this.oldPPayMethodData;
				this.setState({ refresh: true });
			}
		})
	}

	selectDepartment = () => {
		let { POrderInfo } = this.state;
		if (!POrderInfo.companyId) {
			ToastUtil.showWarning('请选择供应商')
			return
		}
		selectIndex = this.getSelectIndex(POrderInfo.organId || '', this.departmentList)
		this.openModal('请选择部门', this.departmentList, selectIndex, this.getDepartment)
	}

	getDepartment = (index) => {
		let { POrderInfo } = this.state;
		POrderInfo.organId = this.departmentList[index].dictKey
		POrderInfo.organName = this.departmentList[index].dictName,
			this.setState({
				POrderInfo,
			}, () => {
				this.closeModal();
			})
	}

	//商品新增/回显
	addProduct = (editData, index) => {
		let { goods, POrderInfo, SOrderInfo, contractTypes } = this.state;
		if (this.tCode !== 'SINONEWS' && !POrderInfo.companyId) {
			ToastUtil.showWarning('请先选择供应商');
			return
		}
		if (this.tCode !== 'SINONEWP' && !SOrderInfo.companyId) {
			ToastUtil.showWarning('请先选择客户');
			return
		}
		if (this.tCode == 'SINONEWP' && !POrderInfo.organId) {
			ToastUtil.showWarning('请先选择部门');
			return
		}
		if (!contractTypes.longTerm) {
			ToastUtil.showWarning('请选择长约类型');
			return false;
		}
		this.props.navigation.navigate('SinoNewOilProductFormPage', {
			type: 'SinoNewOrderBaseInfoPage',
			tCode: this.tCode,
			/* companyId: this.tCode !== 'SINONEWS' ? POrderInfo.companyId : SOrderInfo.companyId,//非销售
			companyName: this.tCode !== 'SINONEWS' ? POrderInfo.companyName : SOrderInfo.companyName,//非销售
			companyIdBuy: SOrderInfo.companyId,
			companyNameBuy: SOrderInfo.companyName, */
			companyId: SOrderInfo.companyId,
			companyName: SOrderInfo.companyName,
			companyIdBuy: POrderInfo.companyId,
			companyNameBuy: POrderInfo.companyName,
			editData,
			goodsList: goods,
			orderId: this.orderId,
			sellerCompanyId: SOrderInfo.companyId,
			organId: POrderInfo.organId,
			groupOnoff: this.groupOnoff,
			productIndex: index,
			callBack: (data) => {
				if (editData) {
					goods[index] = data;
				} else {
					goods.push(data);
				}
				this.profit = this.getProfit(goods);
				goods && goods.forEach(item => {
					this.groupOnoff = item.bizTeamId;
				})
				if (goods && !goods.length) {
					this.groupOnoff = null;
				}
				this.setState({ goods }, () => {
					console.log('中新油-', goods)
				})
			}
		})
	}

	delGoods = (index) => {
		let { goods } = this.state;
		goods.splice(index, 1);
		this.profit = this.getProfit(goods);
		//删除最后一个 制成null
		if (goods && !goods.length) {
			this.groupOnoff = null;
		}
		this.setState({ goods });
	}

	delPayMethod = (index) => {
		let { payMethod } = this.state;
		payMethod.splice(index, 1);
		this.setState({ payMethod });
	}

	// deliveryClick = (radioKey, radioValue) => {
	// 	let { otherInfo } = this.state;
	// 	otherInfo.deliveryType = radioKey;
	// 	this.setState({ otherInfo })
	// }

	termClick = (radioKey, radioValue) => {
		let { otherInfo } = this.state;
		otherInfo.priceTerm = radioKey;
		this.setState({ otherInfo });
	}

	getSelectIndex = (key, data) => {
		let selectIndex = -1;
		data && data.map((item, index) => {
			if (item.dictKey === key) {
				selectIndex = index
			}
		})
		return selectIndex;
	}

	closeModal = () => {
		let { modalObj } = this.state;
		modalObj.currIsVisible = false;
		this.setState({ modalObj });
	}

	currencyModalInit = (index) => {
		this.currCurrencyIndex = index;
		let { fee } = this.state;
		let selectIndex = this.getSelectIndex(fee[index].currency, this.currencyData);

		this.openModal('请选择币种', this.currencyData, selectIndex, this.getCurrency);
	}

	getCurrency = (index) => {
		let { fee } = this.state;
		let { dictKey, dictName } = this.currencyData[index];
		fee[this.currCurrencyIndex].currency = dictKey;
		fee[this.currCurrencyIndex].currencyName = dictName;
		this.closeModal();
	}

	feeInput = (value, index) => {
		let { fee } = this.state;
		fee[index].feeAmt = value;
	}
	// 长约类型
	selectType = () => {
		let { POrderInfo, SOrderInfo, payMethod, contractTypes } = this.state;
		if (this.tCode !== 'SINONEWS' && !POrderInfo.companyId) {
			ToastUtil.showWarning('请先选择供应商');
			return
		}
		if (this.tCode !== 'SINONEWP' && !SOrderInfo.companyId) {
			ToastUtil.showWarning('请先选择客户');
			return
		}
		if (this.tCode == 'SINONEWP' && !POrderInfo.organId) {
			ToastUtil.showWarning('请先选择部门');
			return
		}
		let selectIndex = this.getSelectIndex(contractTypes.longTerm || '', this.contractType);
		this.openModal('请选择长约类型', this.contractType, selectIndex, this.getType)
	}
	// 长约类型数据回调
	getType = (index) => {
		let { contractTypes } = this.state;
		let { dictKey, dictName, } = this.contractType[index];
		contractTypes.longTerm = dictKey; // 长约类型 key
		contractTypes.longTermName = dictName; // 长约类型name 

		this.closeModal();
	}

	_setEndAddress = () => {
		let { otherInfo } = this.state;
		let { endAddressId } = otherInfo || {};
		let selectIndex = this.getSelectIndex(endAddressId, this.endAddressData);
		this.openModal('请选择目的港', this.endAddressData, selectIndex, (index) => {
			otherInfo.endAddress = this.endAddressData[index].dictName;
			otherInfo.endAddressId = this.endAddressData[index].dictKey
			this.closeModal();
		})
	}

	payMethodModalInit(type, index) {
		let { POrderInfo, SOrderInfo, payMethod } = this.state;
		if (type == 'P' && !POrderInfo.companyId) {
			ToastUtil.showWarning('请先选择供应商');
			return false
		}
		if (type == 'S' && !SOrderInfo.companyId) {
			ToastUtil.showWarning('请先选择客户');
			return false
		}
		this.currPayMethod.type = type;
		this.currPayMethod.position = index;
		let selectIndex = this.getSelectIndex(payMethod[index][`${type}PayMethod`].payMethod, this[`${type}PayMethodData`]);
		this.openModal('请选择付款方式', this[`${type}PayMethodData`], selectIndex, this.getPayMethod)
	}

	payMethodInput = (type, index, key, value) => {
		let { payMethod } = this.state;
		payMethod[index][`${type}PayMethod`][key] = value;
	}

	getPayMethod = (index) => {
		let { position, type } = this.currPayMethod;
		let { payMethod } = this.state;

		let { dictKey, dictName, segment, segment1 } = this[`${type}PayMethodData`][index]
		payMethod[position][`${type}PayMethod`].payMethod = dictKey;
		payMethod[position][`${type}PayMethod`].payMethodName = dictName;
		payMethod[position][`${type}PayMethod`].paymentRatio = segment;
		payMethod[position][`${type}PayMethod`].paymentDays = segment1;
		this.closeModal();
		//为授信条款时弹出提示框
		// if (segment == 'TRUE') {
		// 	this.setState({ modalVisible: true })
		// }
	}


	addressInput = (key, value) => {
		let { otherInfo } = this.state;
		otherInfo[key] = value;
	}

	openModal(title, listData, index, cb) {
		let { modalObj } = this.state;
		modalObj.currIsVisible = true;
		modalObj.currSelectIndex = index;
		modalObj.currTitle = title;
		modalObj.currlistData = listData;
		modalObj.currCb = cb;
		this.setState({ modalObj }, () => {
		});
	}

	openDatePicker = (type) => {
		this.dateObj.type = type;
		let { deliveryTime } = this.state[`${type}OrderInfo`];
		deliveryTime = deliveryTime || '';
		let dateArr = deliveryTime.split('-');
		this.dateObj.startDate = dateArr[0] ? moment(new Date(dateArr[0])).format('YYYY-MM-DD') : '';
		this.dateObj.endDate = dateArr[1] ? moment(new Date(dateArr[1])).format('YYYY-MM-DD') : '';
		this.setState({ openDatePicker: true })
	}

	getParams = (operateType) => {
		let { POrderInfo, SOrderInfo, payMethod, fee, goods, otherInfo, contractTypes } = this.state;
		let sendData = {
			operateType: operateType == 'NEXT' ? 'SAVE' : operateType,
			zxyOrderItemTOs: goods,
			zxyOrderFeeTOs: fee,
			remark: otherInfo.remark
		};
		let PPayMethod = [], SPayMethod = [];
		POrderInfo = { ...POrderInfo, ...otherInfo };
		SOrderInfo = { ...SOrderInfo, ...otherInfo };
		POrderInfo.orderType = 'P';
		SOrderInfo.orderType = 'S';
		payMethod.map(item => {
			PPayMethod.push(item.PPayMethod);
			SPayMethod.push(item.SPayMethod);
		})
		if (this.tCode === 'SINONEWP') {
			POrderInfo.bizMode = '0';
			POrderInfo.longTerm = contractTypes.longTerm;
			sendData.zxyOrderInfoTO = POrderInfo;
			sendData.zxyOrderPayMethodTOs = PPayMethod;
		} else if (this.tCode === 'SINONEWS') {
			SOrderInfo.bizMode = '0';
			SOrderInfo.longTerm = contractTypes.longTerm;
			sendData.zxyOrderInfoTO = SOrderInfo;
			sendData.zxyOrderPayMethodTOs = SPayMethod;
		} else {
			POrderInfo.bizMode = '1';
			SOrderInfo.bizMode = '1';
			SOrderInfo.longTerm = contractTypes.longTerm;
			POrderInfo.longTerm = contractTypes.longTerm;
			sendData.oppoPurOrderInfoTO = POrderInfo;
			sendData.oppoSaleOrderInfoTO = SOrderInfo;
			sendData.zxyPurOrderPayMethodTOs = PPayMethod;
			sendData.zxySaleOrderPayMethodTOs = SPayMethod;
		}
		return sendData;
	}

	validateParams = () => {
		let { POrderInfo, SOrderInfo, payMethod, fee, goods, otherInfo, contractTypes } = this.state;
		if (!contractTypes.longTerm) {
			ToastUtil.showWarning('请选择长约类型');
			return false;
		}
		if (this.tCode === 'SINONEWP') {
			if (!POrderInfo.companyId) {
				ToastUtil.showWarning('请选择供应商');
				return false;
			}
			if (!POrderInfo.organId) {
				ToastUtil.showWarning('请选择部门')
				return
			}
			if (!POrderInfo.deliveryTime) {
				ToastUtil.showWarning('请选择最晚装船日期');
				return false;
			}
		} else if (this.tCode === 'SINONEWS') {
			if (!SOrderInfo.companyId) {
				ToastUtil.showWarning('请选择客户');
				return false;
			}
			// if (!otherInfo.deliveryType) {
			// 	ToastUtil.showWarning('请选择交货方式');
			// 	return false;
			// }
			if (!SOrderInfo.deliveryTime) {
				ToastUtil.showWarning('请选择最晚装船日期');
				return false;
			}
		} else if (this.tCode === 'SINONEWC') {
			if (!POrderInfo.companyId) {
				ToastUtil.showWarning('请选择供应商');
				return false;
			}
			if (!SOrderInfo.companyId) {
				ToastUtil.showWarning('请选择客户');
				return false;
			}
			if (!SOrderInfo.deliveryTime || !POrderInfo.deliveryTime) {
				ToastUtil.showWarning('请选择最晚装船日期');
				return false;
			}
		}
		if (!goods.length) {
			ToastUtil.showWarning('请添加商品');
			return false;
		}
		if (!otherInfo.endAddress) {
			ToastUtil.showWarning('请添加目的港');
			return false;
		}


		let baseDateRepeat = false;
		goods.map((item, index) => {
			goods.map((itemC, indexC) => {
				if (item.baseDateSettle != itemC.baseDateSettle && index !== indexC) {
					baseDateRepeat = true;
				}
			})
		})
		if (this.tCode === 'SINONEWS' && baseDateRepeat) {
			ToastUtil.showWarning('添加商品结算基准日期必须一样');
			return false;
		}

		if (!otherInfo.priceTerm) {
			ToastUtil.showWarning('请选择贸易条件');
			return false;
		}
		if (otherInfo.priceTerm === 'OTHER' && !otherInfo.priceTermDesc) {
			ToastUtil.showWarning('请输入贸易条件');
			return false;
		}

		let PPaymentRatioSum = 0, SPaymentRatioSum = 0;
		let payMethodFlag = false;
		let paymentDaysFlag = false;
		payMethod.map(item => {
			PPaymentRatioSum = item.PPayMethod ? MethodUtil.countObj.add(PPaymentRatioSum, Number.parseFloat(item.PPayMethod.paymentRatio)) : 0;
			SPaymentRatioSum = item.SPayMethod ? MethodUtil.countObj.add(SPaymentRatioSum, Number.parseFloat(item.SPayMethod.paymentRatio)) : 0;
			if ((item.PPayMethod && !item.PPayMethod.payMethod) || (item.SPayMethod && !item.SPayMethod.payMethod)) {
				payMethodFlag = true;
			}
			if ((item.PPayMethod && item.PPayMethod.payMethodName && item.PPayMethod.payMethodName.indexOf('@@') != -1 && (!item.PPayMethod.paymentDays || item.PPayMethod.paymentDays <= 0))
				|| item.SPayMethod && item.SPayMethod.payMethodName && item.SPayMethod.payMethodName.indexOf('@@') != -1 && (!item.SPayMethod.paymentDays || item.SPayMethod.paymentDays <= 0)) {
				paymentDaysFlag = true
			}
		})
		if (payMethodFlag) {
			ToastUtil.showWarning('请选择付款方式');
			return false;
		}
		if (this.tCode == 'SINONEWP' && PPaymentRatioSum != 100) {
			ToastUtil.showWarning('付款比例总和必须为100%');
			return false;
		}
		if (this.tCode == 'SINONEWS' && SPaymentRatioSum != 100) {
			ToastUtil.showWarning('付款比例总和必须为100%');
			return false;
		}
		if (this.tCode == 'SINONEWC' && (PPaymentRatioSum != 100 || SPaymentRatioSum != 100)) {
			ToastUtil.showWarning('付款比例总和必须为100%');
			return false;
		}
		if (paymentDaysFlag) {
			ToastUtil.showWarning('付款天数必须大于0');
			return false;
		}
		return true;
	}

	_modyfiy = (goodsList) => {
		let { goods } = this.state;
		if (goods.length && goodsList.length) {
			goods.map((item) => {
				for (let i = 0; i < goodsList.length; i++) {
					if (item.goodsId === goodsList[i].goodsId) {
						item = Object.assign({}, item, goodsList[i]);
					}
				}
				return item;
			})
		}
		return goods || goodsList || [];
	}

	save = async (operateType) => {
		console.log("点击了")
		if (this.requesting) return;
		if (!this.validateParams()) return;
		console.log("进来了", operateType === 'NEXT' ? "下一步" : "保存")
		this.requesting = true;
		this.setState({ status: 'loading' });
		let response = await HTTP.POST(API_GENERATE(this.tCode === 'SINONEWC' ? API.ZXY_CLOSE_ORDER_ADD : API.ZXY_ORDER_ADD), this.getParams(operateType));
		this.setState({ status: 'data' });
		if (response) {
			ToastUtil.showSuccess('操作成功').then(() => {
				if (this.tCode == 'SINONEWS' && operateType === 'NEXT') {
					// 返回的数据在赋值给原来的对象， 防止关联页面返回 orderId号丢失
					this.setState({
						SOrderInfo: response.zxyOrderInfoTO,
						goods: this._modyfiy(response.zxyOrderItemTOs)
					}, () => {
						navigationSeevice.navigate('SinoNewRelevanceOrderList', { sendData: response });
					})
				} else {
					OrderNewOilCreactService.reset(this.tCode);
				}
			}).catch(err => {
				this.requesting = false;
			})
		} else {
			this.requesting = false;
		}
	}

	orderDel = async () => {
		Alert.alert(
			'提示', `是否删除此订单？`,
			[
				{ text: '取消', },
				{
					text: '确认', onPress: async () => {
						this.requesting = true;
						this.setState({ status: 'loading' });
						let reqUrl = this.status == 'RPT_AUDIT_UNPASS' ? API.ZXY_DELETE_ORDER : API.ZXY_ORDER_DELETE;
						let response = await HTTP.GET(API_GENERATE(reqUrl), { orderId: this.orderId });
						this.setState({ status: 'data' });
						if (response) {
							ToastUtil.showSuccess('订单删除成功').then(() => {
								OrderNewOilCreactService.reset(this.tCode);
							}).catch(err => {
								this.requesting = false;
							})
						} else {
							this.requesting = false;
						}
					}
				},
			],
		)
	}

	// 查看审批流
	getApproveProcess = async () => {
		this.setState({ status: 'loading' })
		let res = await HTTP.GET(API_GENERATE(API.ZXY_APPROVAL_PROCESS), {
			bizId: this.orderId,
			processInstanceId: this.processInstanceId
		});
		res.forEach(item => {
			if (item.taskName == '领导会签') item.taskName = '风委会成员会签'
		})
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = true;
		lightBoxData.title = '审批进度';
		lightBoxData.rowDataList = res;
		this.setState({
			lightBoxData,
			status: 'data'
		})
	}

	_closeLightBox = () => {
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = false;
		this.setState({ lightBoxData });
	}

	// 化销外采订单跳转订单详情
	goOrderDetail = (purchaseOrderId) => {
		if (!purchaseOrderId) return
		this.props.navigation.navigate('OrderDetailsPage', {
			orderId: purchaseOrderId,
			orderType: 'P'
		})
	}

	_renderPayDialog() {
		return (
			<View>
				<Text style={{ fontSize: 16 * scale, lineHeight: 18 * scale, fontWeight: 'bold' }}>请注意<Text style={{ fontSize: 13 * scale }}>当前选择的价格公式涉及授信，将触发风控委员会领导审批，请提前沟通确认。</Text></Text>
			</View>
		)
	}

	_remarkFocus = () => {
		this.scrollview.scrollTo({ x: 0, y: (this.viewHeight + 30) * scale, animated: true })
	}
	_onLayout = (event) => {
		if (!this.viewHeight) {
			this.viewHeight = event.nativeEvent.layout.height || 0;
		}
	}

	render() {
		let { lightBoxData, status, modalObj, POrderInfo, SOrderInfo, payMethod, fee, goods, otherInfo,
			purchaseOrderStatus, purchaseOrderId, modalVisible, contractTypes } = this.state;
		return (
			<View style={{ flex: 1 }}>
				<NavigationEvents
					onDidBlur={async ({ action }) => {
						this.requesting = false;
					}}
				/>
				<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={Header.HEIGHT + 20}>
					<ScrollView ref={(element) => this.scrollview = element} showsVerticalScrollIndicator={false} keyboardShouldPersistTaps={'handled'}>
						<View onLayout={(event) => this._onLayout(event)}>
							{
								this.status == 'RPT_AUDIT_UNPASS' ? (
									<View style={{
										flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', height: 40 * scale,
										paddingLeft: 24 * scale,
										paddingRight: 25 * scale,
									}}>
										<Text style={{ color: '#0E7FFD' }} onPress={() => {
											this.getApproveProcess();
										}}>查看审批流程</Text>
									</View>
								) : null
							}

							{
								purchaseOrderStatus && purchaseOrderId ? (
									<View style={{ backgroundColor: '#F4F7FE' }}>
										<View style={styles.orderTips}>
											<View style={{ flexDirection: 'row', justifyContent: 'flex-start' }}>
												<Text>关联化销外采订单</Text>
												{
													purchaseOrderStatus == 1 ? <Text style={{ color: 'red' }}>（已作废）</Text> : <Text >（正常）</Text>
												}
											</View>

											<TouchableOpacity activeOpacity={.8} onPress={() => { this.goOrderDetail(purchaseOrderId) }}>
												<Text style={{ color: '#0E7FFD' }}>{purchaseOrderId}</Text>
											</TouchableOpacity>
										</View>
									</View>
								) : null
							}

							<View style={{ backgroundColor: '#F4F7FE' }}>
								{this.tCode !== 'SINONEWS' ? <FormItem styleObj={{ labelColor: '#34475F' }} required={true} label='供应商' value={POrderInfo.companyName} placeHolder='请选择供应商名称' handleCallBack={() => { this.gotoSupplier('P') }} /> : null}
								{(this.tCode !== 'SINONEWS' && POrderInfo.creditLevel) ? <Text style={styles.zxpj}>资信评级:{POrderInfo.creditLevel}级</Text> : null}
								{this.tCode !== 'SINONEWP' ? <FormItem styleObj={{ labelColor: '#34475F' }} required={true} label='客户名称' value={SOrderInfo.companyName} placeHolder='请选择客户名称' handleCallBack={() => { this.gotoSupplier('S') }} /> : null}
								{(this.tCode !== 'SINONEWP' && SOrderInfo.creditLevel) ? <Text style={styles.zxpj}>资信评级:{SOrderInfo.creditLevel}级</Text> : null}
								{this.tCode == 'SINONEWP' ? <FormItem styleObj={{ labelColor: '#34475F' }} required={true} label='采购给/部门' value={POrderInfo.organName} placeHolder='请选择部门' handleCallBack={() => { this.selectDepartment() }} /> : null}
								<FormItem styleObj={{ labelColor: '#34475F' }} required={true} label='长约类型' value={contractTypes.longTermName || ''} placeHolder='请选择长约类型' handleCallBack={() => { this.selectType() }} />
								<View style={{ backgroundColor: '#FFFFFF' }}>
									<View style={[goods.length ? styles.border : null, styles.blockPadding, styles.spaceBetween]}>
										<Text style={styles.firstTitle}>商品信息</Text>
										<Text style={[styles.firstTitle, { color: '#0E7FFD', fontSize: 14 * scale }]} onPress={() => this.addProduct()}>新增商品</Text>
									</View>
									{goods.map((item, index) => {
										return (
											<ProductInfoItem
												key={index}
												isCreate={true}
												tCode={this.tCode}
												data={{ item, index }}
												delGoods={(index) => { this.delGoods(index) }}
												itemPress={(item, index) => { this.addProduct(item, index) }}
											/>
										)
									})}
								</View>
								<View style={{ marginTop: 12 * scale, backgroundColor: '#FFFFFF' }}>
									<Text style={[styles.firstTitle, styles.blockPadding]}>交易信息</Text>
								</View>
								<View style={{ backgroundColor: '#FFFFFF' }}>
									<FormItem border={true} required={true} rightContent={
										<View>
											<View style={{ flexDirection: 'row', width: 295 * scale, paddingLeft: 28 * scale, flexWrap: 'wrap' }}>
												{this.termsData.map((item, index) => {
													return <View key={index} style={{ paddingBottom: 10 * scale }}>
														<RadioButton selectedKey={otherInfo.priceTerm} radioKey={item.dictKey} radioValue={item.dictKey === 'OTHER' ? '其他' : item.dictKey} selectedChange={this.termClick} />
													</View>
												})}
											</View>
											{otherInfo.priceTerm === 'OTHER' ? < TextInput underlineColorAndroid="transparent"
												style={[styles.border, { marginLeft: 28 * scale, marginRight: 25 * scale, maxWidth: 270 * scale }]}
												defaultValue={otherInfo.priceTermDesc}
												maxLength={120}
												placeholder='请输入'
												onChangeText={(txt) => {
													otherInfo.priceTermDesc = txt;
												}}
											/> : null}</View>
									} label='贸易条件' />
									{
										payMethod && payMethod.map((item, index) => {
											let { PPayMethod, SPayMethod } = item;
											return <View key={index}>
												<View style={{ flexDirection: 'row-reverse' }}>
													<Text style={[styles.firstTitle, { color: '#0E7FFD', width: 120 * scale, textAlign: 'right', paddingRight: 24.5 * scale }]} onPress={() => { this.delPayMethod(index) }}>删</Text>
												</View>
												{
													PPayMethod ?
														<View style={index === payMethod.length - 1 && !SPayMethod ? null : styles.border}>
															<FormItem required={true} tagLogo={this.tCode === 'SINONEWC' ? purchaseTag : null} label='付款方式 ' value={PPayMethod.payMethodName} placeHolder='请选择'
																handleCallBack={() => { this.payMethodModalInit('P', index) }} />
															<View>
																<FormItem editable={false} styleObj={{ size: 'small' }} label='比例' type='input' placeHolder='请选择' value={PPayMethod.paymentRatio} rightText='%' />
																<FormItem editable={false} styleObj={{ size: 'small' }} label='期限' type='input' placeHolder='请选择' value={PPayMethod.paymentDays} rightText='天' />
															</View>
														</View>
														: null
												}
												{
													SPayMethod ?
														<View style={index === payMethod.length - 1 ? null : styles.border}>
															<FormItem required={true} tagLogo={this.tCode === 'SINONEWC' ? saleTag : null} label='付款方式 ' value={SPayMethod.payMethodName} placeHolder='请选择'
																handleCallBack={() => { this.payMethodModalInit('S', index) }} />
															<View>
																<FormItem editable={false} styleObj={{ size: 'small' }} label='比例' type='input' placeHolder='请选择' value={SPayMethod.paymentRatio} rightText='%' />
																<FormItem editable={false} styleObj={{ size: 'small' }} label='期限' type='input' placeHolder='请选择' value={SPayMethod.paymentDays} rightText='天' />
															</View>
														</View>
														: null
												}
											</View>
										})}
									<View style={[styles.border, { alignItems: 'center' }]}>
										<Text style={[styles.firstTitle, { color: '#0E7FFD', textAlign: 'center', fontSize: 14 * scale, width: 250 * scale, alignItems: 'center' }]} onPress={this.addPayMethod}>增加付款方式</Text>
									</View>
									{/* {this.tCode === 'SINONEWS' ? <FormItem required={true} border={true} rightContent={
								<View style={{ flexDirection: 'row', width: 295 * scale, paddingLeft: 28 * scale, flexWrap: 'wrap' }}>
									{this.deliveryData.map((item, index) => {
										return <View key={index} style={{ paddingBottom: 10 * scale }}>
											<RadioButton selectedKey={otherInfo.deliveryType} radioKey={item.dictKey} radioValue={item.dictName} selectedChange={this.deliveryClick} />
										</View>
									})}
								</View>
							} label='交货方式' handleCallBack={this.deliveryClick} /> : null} */}
									{this.tCode !== 'SINONEWS' ? <FormItem required={true} border={true} rightIcon={timeImage} rightIconStyle={{ width: 16 * scale, height: 20 * scale, tintColor: '#333' }} style={{ width: 14 * scale, height: 16 * scale }} tagLogo={this.tCode === 'SINONEWC' ? purchaseTag : null} label='最晚装船日期' value={POrderInfo.deliveryTime} placeHolder='请选择' handleCallBack={() => { this.openDatePicker('P') }} /> : null}
									{this.tCode !== 'SINONEWP' ? <FormItem required={true} border={true} rightIcon={timeImage} rightIconStyle={{ width: 16 * scale, height: 20 * scale, tintColor: '#333' }} style={{ width: 14 * scale, height: 16 * scale }} tagLogo={this.tCode === 'SINONEWC' ? saleTag : null} label='最晚装船日期' value={SOrderInfo.deliveryTime} placeHolder='请选择' handleCallBack={() => { this.openDatePicker('S') }} /> : null}
									<FormItem type='mutiInput' returnKeyType={'default'} inputStyle={{ paddingTop: 10 * scale, paddingBottom: 10 * scale }} border={true} tagLogo={this.tCode === 'SINONEWC' ? purchaseTag : null} label='出库地 ' value={otherInfo.beginAddress} placeHolder='请输入发货地址' handleCallBack={(str) => { this.addressInput('beginAddress', str) }} />
									<FormItem required={true} label='目的港' value={otherInfo.endAddress} placeHolder='请选择' handleCallBack={() => { this._setEndAddress() }} />
								</View>

								<View style={{ marginTop: 12 * scale, backgroundColor: '#FFFFFF' }}>
									<View style={[styles.border, styles.blockPadding]}>
										<Text style={styles.firstTitle}>费用预估</Text>
									</View>
									{fee.map((item, index) => {
										return <FormItem key={index} border={true} keyboardType='numeric' type={'input'} label={item.logisticFundTypeName} value={item.feeAmt} placeHolder='请输入' rightText={item.currencyName || '美元'} rightIcon={arrowDownImage} textPress={() => { this.currencyModalInit(index) }} handleCallBack={(str) => { this.feeInput(str, index) }} />
									})}
									{this.tCode === 'SINONEWC' ? <View style={{ height: 50 * scale, flexDirection: 'row-reverse', }}>
										<Text style={{ lineHeight: 50 * scale, paddingRight: 24.5 * scale }}>美元</Text>
										<View style={{ height: 50 * scale, paddingTop: 14 * scale, paddingBottom: 14 * scale }}>
											{currency(this.profit, '', { valueColor: '#0E7FFD' })}
										</View>
										<Text style={{ lineHeight: 50 * scale }}>销售毛利：</Text>
									</View> : null}
								</View>
								{
									this.tCode === 'SINONEWC' ? <View style={[styles.blockItem, styles.blockPadding, { justifyContent: 'space-between', flexDirection: 'row' }]}>
										<Text style={styles.firstTitle}>品质损耗</Text>
										<Text style={[styles.firstTitle, { fontSize: 14 * scale }]}>品质数量背对背，我司不承担损耗</Text>
									</View> : null
								}
								<View style={[styles.blockItem, styles.blockPadding]}>
									<Text style={styles.firstTitle}>送审备注</Text>
									<TextInput onFocus={this._remarkFocus} style={styles.textArea} defaultValue={otherInfo.remark + ''} multiline={true} numberOfLines={4} placeholder='限定200字' onChangeText={(str) => {
										otherInfo.remark = str;
									}} />
									<View style={[styles.spaceBetween, { marginTop: 20 * scale, marginBottom: 20 * scale }]}>
										{
											this.tCode !== 'SINONEWS' ?
												<Button type='fill' text='提交'
													btnStyle={{ flex: 1, marginRight: 8 * scale }}
													onPress={() => { this.save('SUBMIT') }} />
												: null
										}
										{
											this.tCode == 'SINONEWS' || (this.tCode !== 'SINONEWS' && !this.orderId) ?
												<Button type={this.tCode !== 'SINONEWS' ? 'outline' : 'fill'} text='保存'
													btnStyle={{ flex: 1, marginRight: 8 * scale }}
													onPress={() => { this.save('SAVE') }} />
												: null
										}
										{
											this.orderId ?
												<Button text={'删除'}
													btnStyle={{ flex: 1, backgroundColor: style.color.lightRed, borderWidth: 0, marginRight: 8 * scale }}
													onPress={() => { this.orderDel() }} />
												: null
										}
										{
											this.tCode == 'SINONEWS' ?
												<Button type='outline' text={'下一步'}
													btnStyle={{ flex: 1 }}
													onPress={() => { this.save('NEXT') }} />
												: null
										}
									</View>
								</View>
							</View>
						</View>
					</ScrollView>
					<Common type="modal" demoData={(
						<Common type="listRadio" selectIndex={modalObj.currSelectIndex} title={modalObj.currTitle} listData={modalObj.currlistData || []} selectCallBack={modalObj.currCb} />
					)} isVisible={modalObj.currIsVisible} closeCallballFn={this.closeModal} />

					{/**付款方式为授信条款时提示 */}
					<CommonDialog
						modalVisible={modalVisible}
						title={'提示'}
						confirmBtnText={'确认'}
						onClosePress={() => { this.setState({ modalVisible: false }) }}
						onConfirmPress={() => { this.setState({ modalVisible: false }) }
						}
						renderCustom={this._renderPayDialog} />

					<DateGapPicker
						isVisible={this.state.openDatePicker}
						date={this.dateObj}
						double={true}
						cb={(newDate) => {
							this.setState({ openDatePicker: false })
							if (!newDate) return;
							let { type } = this.dateObj;
							let { startDate, endDate } = newDate;
							startDate = startDate ? moment(startDate).format('YYYY/MM/DD') : '';
							endDate = endDate ? moment(endDate).format('YYYY/MM/DD') : '';
							this.state[`${type}OrderInfo`].deliveryTime = `${startDate}-${endDate}`;
							this.setState({ refresh: true });
						}} />
					{
						status == 'loading' ? (<View style={{ position: 'absolute', height: '100%', width: '100%', top: 0 }}>
							<PageStatusIndex status={status} />
						</View>
						) : null
					}

					{/* 审批流 */}
					<ProgressModal {...lightBoxData} />
				</KeyboardAvoidingView>
			</View>
		)
	}
}

const styles = StyleSheet.create({
	firstTitle: {
		fontSize: 16 * scale,
		color: '#000000',
		height: 44 * scale,
		lineHeight: 44 * scale,
		fontWeight: 'bold'
	},
	border: {
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: '#E3E7F0',
	},
	blockPadding: {
		paddingLeft: 13 * scale,
		paddingRight: 24.5 * scale,
	},
	blockItem: {
		marginTop: 12 * scale,
		backgroundColor: '#FFFFFF',
	},
	spaceBetween: {
		flexDirection: 'row',
		justifyContent: 'space-between'
	},
	textArea: {
		height: 64 * scale,
		borderWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: '#E3E7F0',
	},
	goodsName: {
		height: 42 * scale,
		lineHeight: 42 * scale,
		fontSize: 14 * scale,
		color: '#000000'
	},
	orderTips: {
		backgroundColor: '#fff',
		marginTop: 14 * scale,
		height: 42 * scale,
		paddingLeft: 22 * scale,
		paddingRight: 22 * scale,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
	},
	zxpj: {
		fontSize: 13 * scale,
		paddingRight: 35 * scale,
		color: '#777',
		textAlign: 'right'
	},
})


